const bodyP = require('body-parser'),
    router = require('./routers'),
    express = require('express'),
    app = express(),
    path = require('path'),
    parseurl = require('parseurl'),
    fs = require('fs'),
    session = require('express-session'),
    mongoStore = require('connect-mongo')(session),
    db = require('mongoose'),
    jwt = require('jsonwebtoken'),
    compression = require('compression')
    // multer = require('multer'),
    // upload = multer()

db.connect('mongodb://localhost/test')
// 处理application/json
app.use(bodyP.json())
// 处理application/xwww-form-urlencoded
app.use(bodyP.urlencoded())
app.use(compression())
// 处理 multipart/form-data
// app.use(upload.single())

app.use(session({
    secret: 'baozi',
    resave: false,
    saveUninitialized: true
}))

// default to app.use('/', cb);
app.use(function (req, res, next) {
    // if (!req.header('guest')) {
    let token = req.header('token')

    if (req.session.token && req.session.token === token) {
        try {
            let decodedObj = jwt.verify(token, 'secret')
            req.session.account = decodedObj.iss
            next()
            return false
        } catch (error) {
            res.send({reason: error.message, result: 'failed', error_code: 500010})
            return false
        }
        // } else {
        //     res.send({reason: 'user permission is required !', result: 'failed', error_code: 500010})
        //     return false
        // }
    }
    next()
})

app.use(router)

app.use('/assets', express.static(path.resolve(__dirname, 'assets')))
// app.use(express.static(path.resolve(__dirname, '../public')))
// disable web cache on browser
app.disable('view cache')
// fix 304
app.disable('etag')

db.connection.on('error', function (e) { console.error(e, 'mg connection error') })
db.connection.once('open', function () { console.log('mg open success') })

app.get('/', function (req, res) {
    res.header('Cache-Control', 'no-cache, no-store, must-revalidate')
    res.header('Pragma', 'no-cache')
    res.header('Expires', 0)
    const html = fs.readFileSync(path.resolve(__dirname, '../dist/index.html'), 'utf-8')
    res.send(html)
})

app.listen(8089)
console.log('set listener okay at 8089')
